<template>
  <el-col :span="8">
    <search />
  </el-col>
  <el-col :span="2">
    <div class="logUser-avatar">
      <img
        ref="avaTriggInCard"
        :src="user.avatar"
        alt=""
        @click="showInfoCard = !showInfoCard"
      />
      <info-card
        style="margin-top: 12px"
        v-model="showInfoCard"
        :trigger-ele="avaTriggInCard"
        :userData="user"
      >
      </info-card>
    </div>
  </el-col>
  <el-col :span="7">
    <div class="select-menu">
      <ul>
        <li>
          <span @click="turnPage('messages')" title="消息" class="menu-icon">
            <Badge :value="messagesStore.unReadMessCouAll">
              <SvgIcon
                :class="{
                  'menu-icon__item': true,
                  'is-actived': currentTitle === '消息',
                }"
                icon-class="message"
              />
            </Badge>
          </span>
        </li>
        <li>
          <span @click="turnPage('contact')" title="通讯录" class="menu-icon">
            <Badge :value="applicationList.size!">
              <SvgIcon
                :class="{
                  'menu-icon__item': true,
                  'is-actived': currentTitle === '通讯录',
                }"
                icon-class="contact"
              />
            </Badge>
          </span>
        </li>
        <li>
          <span title="动态" class="menu-icon" @click="openDynamic"
            ><Badge :circle="dynamicDatas.isHasNew">
              <SvgIcon popper-class="menu-icon__item" icon-class="moments" /></Badge
          ></span>
        </li>
        <li ref="setupEle">
          <span title="设置" class="menu-icon" @click="showSetup = true">
            <SvgIcon icon-class="setup" popper-class="menu-icon__item"
          /></span>
          <set-up :father-ele="setupEle" v-model:show="showSetup"></set-up>
        </li>
      </ul>
    </div>
  </el-col>
  <el-col :span="3"
    ><div class="select-more">
      <SvgIcon
        icon-class="add"
        popper-class="menu-icon__item select-more__icon"
        @click="showMenu = !showMenu"
      />
      <more-menu v-model="showMenu"></more-menu></div
  ></el-col>
  <dynamic v-model="showDynamic" :usr-info="user"></dynamic>
</template>

<script lang="ts" setup>
import { ref, watch, nextTick } from "vue";
import { useRouter, useRoute } from "vue-router";
import Badge from "../ui-components/badge.vue";
import setUp from "../setup/index.vue";
import infoCard from "../infoCard.vue";
import dynamic from "../dynamic/index.vue";
import search from "../search/index.vue";
import { useUserPinia } from "@/pinia/user";
import { useMessagePinia } from "@/pinia/messages";
import { useFriendPinia } from "@/pinia/friend";
import LoadingBar from "@/plugins/loadingBar";
import { ElMessage } from "element-plus";
import { source, refreshAxios } from "@/plugins/http";
import { storeToRefs } from "pinia";
import { Base64 } from "js-base64";
import Cookie from "@/plugins/cookie";
import moreMenu from "./menu.vue";
import { useDynamicPinia } from "@/pinia/dynamic";

const router = useRouter();
const route = useRoute();
const userStore = useUserPinia();
const messagesStore = useMessagePinia();
const friendStore = useFriendPinia();

const { user, applicationList } = storeToRefs(userStore);
const { isRequGetAllFriend } = storeToRefs(friendStore);
const { dynamicDatas } = storeToRefs(useDynamicPinia());

/**
 * 当前用户所点击的图标的标题
 */
const currentTitle = ref<string>("");

watch(
  () => route.name as string,
  (newName: string) => {
    if (newName === "messages" || newName === "chatRecord") currentTitle.value = "消息";
    if (route.path.includes("contact")) currentTitle.value = "通讯录";
  },
  { immediate: true }
);

/**
 * 是否正在请求所有好友数据
 */
const isRequAllFriendsLoad = ref<boolean>(false);
const isCancel = ref<boolean>(false);
/**
 * 页面跳转
 * @param name - 即将跳转的路由的名称
 */
const turnPage: (name: "messages" | "contact") => void = (
  name: "messages" | "contact"
): void => {
  if (name === "messages") {
    if (isRequAllFriendsLoad.value) {
      source.cancel();
      refreshAxios();
      isCancel.value = true;
    }
    if (route.name !== "messages") router.push({ name });
  } else if (isRequGetAllFriend.value) router.push({ name });
  else if (!isRequAllFriendsLoad.value) {
    if (currentTitle.value === "通讯录") currentTitle.value = "";
    // 加载条组件
    const loBar: LoadingBar = new LoadingBar();
    loBar.start();
    isRequAllFriendsLoad.value = true;
    if (isCancel.value) isCancel.value = false;
    friendStore
      .getAllFriends({ slefId: Base64.encode(user.value.userId) })
      .then((data) => {
        isRequAllFriendsLoad.value = false;
        if (data.code === 1) {
          loBar.finsh();
          nextTick(() => {
            currentTitle.value = "通讯录";
            router.push({ name });
          });
        } else if (data.code === -1) {
          Cookie.deleteCookie("token");
          loBar.unMount();
          ElMessage.error("token已失效，请重新登录");
          router.replace({ name: "login" });
        } else {
          loBar.unMount();
          ElMessage({
            type: "error",
            message: "获取好友失败",
            duration: 1500,
          });
        }
      })
      .catch(() => {
        isRequAllFriendsLoad.value = false;
        loBar.unMount();
        if (!isCancel.value)
          ElMessage({
            type: "error",
            message: "获取好友失败",
            duration: 1500,
          });
      });
  }
};

/**
 * 设置组件的父组件
 */
const setupEle = ref<HTMLLinkElement>();
/**
 * 是否打开设置框
 */
let showSetup = ref<boolean>(false);

/**
 * 给用户头像元素一个ref属性
 */
const avaTriggInCard = ref<HTMLElement>(document.createElement("img"));
/**
 * 点击用户头像是否显示个人资料卡片
 */
const showInfoCard = ref<boolean>(false);
/**
 * 是否显示操作更多列表的菜单（当用户点击加号）
 */
const showMenu = ref<boolean>(false);

/**
 * 是否显示打开动态数据弹框
 */
const showDynamic = ref<boolean>(false);
// 打开动态数据弹框
const openDynamic = () => (showDynamic.value = true);
</script>

<style lang="scss" scoped>
.logUser {
  &-avatar {
    position: relative;
    height: 55px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    img {
      cursor: pointer;
      @include setWidHei(42px, 42px);
      border-radius: 50%;
      object-fit: cover;
      transform: translateZ(0);
    }
  }
}

.select {
  &-menu {
    text-align: center;

    & > ul {
      display: inline-block;

      & > li {
        display: inline-block;
      }
    }

    .menu-icon {
      display: table;
      height: 55px;
      display: flex;
      padding: 0 5px;
      margin-right: 14px;
      align-items: center;
      color: $iconColor;
      cursor: pointer;

      &:hover {
        .menu-icon__item {
          opacity: 1;
        }
      }

      &__item {
        opacity: 0.65;
        transition: opacity 0.25s;
      }
    }
  }

  &-more {
    position: relative;
    height: 55px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    &__icon {
      color: #fff;
      margin-right: 10px;
      cursor: pointer;
    }
  }
}

.is-actived {
  opacity: 1 !important;
}
</style>
